package com.cnh.o2o.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cnh.o2o.cache.JedisUtil;
import com.cnh.o2o.dao.ShopCategoryDao;
import com.cnh.o2o.dto.ImageHolder;
import com.cnh.o2o.dto.ShopCategoryExecution;
import com.cnh.o2o.entity.ShopCategory;
import com.cnh.o2o.entity.ShopCategory2;
import com.cnh.o2o.enums.ShopCategoryStateEnum;
import com.cnh.o2o.service.ShopCategoryService;
import com.cnh.o2o.util.ImageUtil;
import com.cnh.o2o.util.PathUtil;

@Service
public class ShopCategoryServiceImpl implements ShopCategoryService {

	@Autowired
	private ShopCategoryDao shopCategoryDao;
	@Autowired
	private JedisUtil.Strings jedisStrings;
	@Autowired
	private JedisUtil.Keys jedisKeys;
	private static String SCLISTKEY = "shopcategorylist";
	private static Logger logger = LoggerFactory.getLogger(ShopCategoryServiceImpl.class);

	@Override
	@Transactional
	public List<ShopCategory2> getShopCategoryList(ShopCategory2 shopCategoryCondition) throws Exception {
		return shopCategoryDao.queryShopCategory(shopCategoryCondition);
	}
/*	public List<ShopCategory> getShopCategoryList(ShopCategory shopCategoryCondition) throws Exception {
		String key = SCLISTKEY;
		List<ShopCategory> shopCategoryList = null;
		ObjectMapper mapper = new ObjectMapper();
		if (shopCategoryCondition == null) {
			// 若查询条件为空,则列出所有首页大类,即parentId为空的店铺类别
			key = key + "_allfirstlevel";
		} else if (shopCategoryCondition != null && shopCategoryCondition.getParent() != null
				&& shopCategoryCondition.getParent().getShopCategoryId() != null) {
			// 若parentId不为空,则列出该parentId下的所有子类别
			key = key + "_parent" + shopCategoryCondition.getParent().getShopCategoryId();
		} else if (shopCategoryCondition != null) {
			// 列出所有子类别,不管其属于哪个类,都列出来
			key = key + "_allsecondlevel";
		}

		if (!jedisKeys.exists(key)) {
			shopCategoryList = shopCategoryDao.queryShopCategory(shopCategoryCondition);
			String jsonString;
			try {
				jsonString = mapper.writeValueAsString(shopCategoryList);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
				logger.error(e.getMessage());
				throw new ShopCategoryOperationException(e.getMessage());
			}
			jedisStrings.set(key, jsonString);
		} else {
			String jsonString = jedisStrings.get(key);
			JavaType javaType = mapper.getTypeFactory()
					.constructParametricType(ArrayList.class,
							ShopCategory.class);
			try {
				shopCategoryList = mapper.readValue(jsonString, javaType);
			} catch (RuntimeException e) {
				e.printStackTrace();
				logger.error(e.getMessage());
				throw new ShopCategoryOperationException(e.getMessage());
			}
		}
		return shopCategoryList;
	}*/

	
	@Override
	public List<ShopCategory2> getFirstLevelShopCategoryList() throws IOException {
		List<ShopCategory2> shopCategoryList = null;
		shopCategoryList = shopCategoryDao.queryFirstLevelShopCategoryList(null);
		return shopCategoryList;
	}
//	@Override
//	@Transactional
//	public List<ShopCategory> getFirstLevelShopCategoryList()
//			throws IOException {
//		String key = SCLISTKEY;
//		List<ShopCategory> shopCategoryList = null;
//		ObjectMapper mapper = new ObjectMapper();
//		if (!jedisKeys.exists(key)) {
//			shopCategoryList = shopCategoryDao
//					.queryShopCategory(shopCategoryCondition);
//			String jsonString = mapper.writeValueAsString(shopCategoryList);
//			jedisStrings.set(key, jsonString);
//		} else {
//			String jsonString = jedisStrings.get(key);
//			JavaType javaType = mapper.getTypeFactory()
//					.constructParametricType(ArrayList.class,
//							ShopCategory.class);
//			shopCategoryList = mapper.readValue(jsonString, javaType);
//		}
//		return shopCategoryList;
//	}
	
	@Override
	public List<ShopCategory2> getAllSecondLevelShopCategory()
			throws IOException {
		List<ShopCategory2> shopCategoryList = null;
		// 当shopCategoryDesc不为空的时候，查询的条件会变为 where parent_id is not null
		shopCategoryList = shopCategoryDao
				.queryAllSecondLevelShopCategory();
		return shopCategoryList;
	}
	
//	@Override
//	@Transactional
//	public List<ShopCategory> getAllSecondLevelShopCategory()
//			throws IOException {
//		String key = SCLISTKEY + "ALLSECOND";
//		List<ShopCategory> shopCategoryList = null;
//		ObjectMapper mapper = new ObjectMapper();
//		if (!jedisKeys.exists(key)) {
//			ShopCategory shopCategoryCondition = new ShopCategory();
//			// 当shopCategoryDesc不为空的时候，查询的条件会变为 where parent_id is not null
//			shopCategoryCondition.setShopCategoryDesc("ALLSECOND");
//			shopCategoryList = shopCategoryDao
//					.queryShopCategory(shopCategoryCondition);
//			String jsonString = mapper.writeValueAsString(shopCategoryList);
//			jedisStrings.set(key, jsonString);
//		} else {
//			String jsonString = jedisStrings.get(key);
//			JavaType javaType = mapper.getTypeFactory()
//					.constructParametricType(ArrayList.class,
//							ShopCategory.class);
//			shopCategoryList = mapper.readValue(jsonString, javaType);
//		}
//		return shopCategoryList;
//	}
	
	@Override
	public ShopCategory getShopCategoryById(Long shopCategoryId) {
		List<ShopCategory2> shopCategoryList = new ArrayList<ShopCategory2>();
		try {
			shopCategoryList = getFirstLevelShopCategoryList();
			shopCategoryList.addAll(getAllSecondLevelShopCategory());
		} catch (IOException e) {
			e.printStackTrace();
		}
		//将shopCategory2转到shopCategory
		List<ShopCategory> scList = turnShopCategory2IntoShopCategory(shopCategoryList);
		for (ShopCategory sc : scList) {
			if (shopCategoryId == sc.getShopCategoryId()) {
				return sc;
			}
		}
		ShopCategory2 sc2 = shopCategoryDao.queryShopCategoryById(shopCategoryId);
		ShopCategory sc = turnShopCategory2IntoShopCategory(sc2);
		if (sc != null) {
			return sc;
		} else {
			return null;
		}

	}
	private List<ShopCategory> turnShopCategory2IntoShopCategory(List<ShopCategory2> shopCategoryList) {
		List<ShopCategory> scList = new ArrayList<ShopCategory>();
		ShopCategory sc = null;
		for (ShopCategory2 sc2 : shopCategoryList) {
			sc = new ShopCategory();
			ShopCategory parentCategory = new ShopCategory();
			parentCategory.setShopCategoryId(sc2.getParentId());
			sc.setParent(parentCategory);
			sc.setShopCategoryId(sc2.getShopCategoryId());
			sc.setCreateTime(sc2.getCreateTime());
			sc.setLastEditTime(sc2.getLastEditTime());
			sc.setPriority(sc2.getPriority());
			sc.setShopCategoryName(sc2.getShopCategoryName());
			sc.setShopCategoryDesc(sc2.getShopCategoryDesc());
			sc.setShopCategoryImg(sc2.getShopCategoryImg());
			scList.add(sc);
		}
		return scList;
	}
	private ShopCategory turnShopCategory2IntoShopCategory(ShopCategory2 sc2) {
		ShopCategory sc = null;
		sc = new ShopCategory();
		ShopCategory parentCategory = new ShopCategory();
		parentCategory.setShopCategoryId(sc2.getParentId());
		sc.setParent(parentCategory);
		sc.setShopCategoryId(sc2.getShopCategoryId());
		sc.setCreateTime(sc2.getCreateTime());
		sc.setLastEditTime(sc2.getLastEditTime());
		sc.setPriority(sc2.getPriority());
		sc.setShopCategoryName(sc2.getShopCategoryName());
		sc.setShopCategoryDesc(sc2.getShopCategoryDesc());
		sc.setShopCategoryImg(sc2.getShopCategoryImg());
		return sc;
	}
	@Override
	@Transactional
	public ShopCategoryExecution addShopCategory(ShopCategory2 shopCategory2,
			ImageHolder thumbnail) {
		if (shopCategory2 != null) {
			shopCategory2.setCreateTime(new Date());
			shopCategory2.setLastEditTime(new Date());
			if (thumbnail != null) {
				addThumbnail(shopCategory2, thumbnail);
			}
			try {
				int effectedNum = shopCategoryDao
						.insertShopCategory(shopCategory2);
				if (effectedNum > 0) {
					//不使用redis
//					String prefix = SCLISTKEY;
//					Set<String> keySet = jedisKeys.keys(prefix + "*");
//					for (String key : keySet) {
//						jedisKeys.del(key);
//					}
					return new ShopCategoryExecution(
							ShopCategoryStateEnum.SUCCESS, shopCategory2);
				} else {
					return new ShopCategoryExecution(
							ShopCategoryStateEnum.INNER_ERROR);
				}
			} catch (Exception e) {
				throw new RuntimeException("添加店铺类别信息失败:" + e.toString());
			}
		} else {
			return new ShopCategoryExecution(ShopCategoryStateEnum.EMPTY);
		}
	}
	
	@Override
	@Transactional
	public ShopCategoryExecution modifyShopCategory(ShopCategory2 shopCategory,
			ImageHolder thumbnail, boolean thumbnailChange) {
		if (shopCategory.getShopCategoryId() != null
				&& shopCategory.getShopCategoryId() > 0) {
			shopCategory.setLastEditTime(new Date());
			if (thumbnail != null /*&& thumbnailChange == true */) {
				ShopCategory2 tempShopCategory = shopCategoryDao
						.queryShopCategoryById(shopCategory.getShopCategoryId());
				if (tempShopCategory.getShopCategoryImg() != null) {
					ImageUtil.deleteFileOrPath(tempShopCategory.getShopCategoryImg());
				}
				addThumbnail(shopCategory, thumbnail);
			}
			try {
				int effectedNum = shopCategoryDao
						.updateShopCategory(shopCategory);
				if (effectedNum > 0) {
					//不使用redis
//					String prefix = SCLISTKEY;
//					Set<String> keySet = jedisKeys.keys(prefix + "*");
//					for (String key : keySet) {
//						jedisKeys.del(key);
//					}
					return new ShopCategoryExecution(
							ShopCategoryStateEnum.SUCCESS, shopCategory);
				} else {
					return new ShopCategoryExecution(
							ShopCategoryStateEnum.INNER_ERROR);
				}
			} catch (Exception e) {
				throw new RuntimeException("更新店铺类别信息失败:" + e.toString());
			}
		} else {
			return new ShopCategoryExecution(ShopCategoryStateEnum.EMPTY);
		}
	}
	
	@Override
	@Transactional
	public ShopCategoryExecution removeShopCategory(long shopCategoryId) {
		if (shopCategoryId > 0) {
			try {
				ShopCategory2 tempShopCategory = shopCategoryDao
						.queryShopCategoryById(shopCategoryId);
				if (tempShopCategory.getShopCategoryImg() != null) {
					ImageUtil.deleteFileOrPath(tempShopCategory.getShopCategoryImg());
				}
				int effectedNum = shopCategoryDao
						.deleteShopCategory(shopCategoryId);
				if (effectedNum > 0) {
//					String prefix = SCLISTKEY;
//					Set<String> keySet = jedisKeys.keys(prefix + "*");
//					for (String key : keySet) {
//						jedisKeys.del(key);
//					}
					return new ShopCategoryExecution(
							ShopCategoryStateEnum.SUCCESS);
				} else {
					return new ShopCategoryExecution(
							ShopCategoryStateEnum.INNER_ERROR);
				}
			} catch (Exception e) {
				throw new RuntimeException("删除店铺类别信息失败:" + e.toString());
			}
		} else {
			return new ShopCategoryExecution(ShopCategoryStateEnum.EMPTY);
		}
	}
	
	@Override
	@Transactional
	public ShopCategoryExecution removeShopCategoryList(
			List<Long> shopCategoryIdList) {
		if (shopCategoryIdList != null && shopCategoryIdList.size() > 0) {
			try {
				List<ShopCategory2> shopCategoryList = shopCategoryDao
						.queryShopCategoryByIds(shopCategoryIdList);
				for (ShopCategory2 shopCategory : shopCategoryList) {
					if (shopCategory.getShopCategoryImg() != null) {
						ImageUtil.deleteFileOrPath(shopCategory.getShopCategoryImg());
					}
				}
				int effectedNum = shopCategoryDao
						.batchDeleteShopCategory(shopCategoryIdList);
				if (effectedNum > 0) {
//					String prefix = SCLISTKEY;
//					Set<String> keySet = jedisKeys.keys(prefix + "*");
//					for (String key : keySet) {
//						jedisKeys.del(key);
//					}
					return new ShopCategoryExecution(
							ShopCategoryStateEnum.SUCCESS);
				} else {
					return new ShopCategoryExecution(
							ShopCategoryStateEnum.INNER_ERROR);
				}
			} catch (Exception e) {
				throw new RuntimeException("删除店铺类别信息失败:" + e.toString());
			}
		} else {
			return new ShopCategoryExecution(ShopCategoryStateEnum.EMPTY);
		}
	}
	@Override
	public List<ShopCategory2> getAllShopCategoryList() throws IOException {
		return shopCategoryDao.queryAllShopCategory();
	}
	private void addThumbnail(ShopCategory2 shopCategory2, ImageHolder thumbnail) {
		String dest = PathUtil.getShopCategoryImagePath();
		String thumbnailAddr = ImageUtil.generateThumbnail(thumbnail, dest);
		shopCategory2.setShopCategoryImg(thumbnailAddr);
	}


	
}
